<template>
	<view class="inspect form">
		<view class="form-header">{{ eventName }}</view>
		<swiper 
			class="carousel" 
			:indicatorDots="true" 
			:current="count" 
			indicator-active-color="#d4237a"
			:disable-touch="true">
			<swiper-item class="carousel-item">
				<form-group ref="report" v-model="reportData" ></form-group>
				<view class="btns">
					<view class="btns-group">
						<button class="btn btn-a" @tap="sendData">下一项（确定）</button>
					</view>
				</view>
			</swiper-item>
			<swiper-item class="carousel-item" v-for="(data, index) in answer_datas" :key="index">
				<view class="form-group" >
					<view class="title">{{data.parent_name}}</view>
					<view class="sub-title">{{data.name}}</view>
					<view class="tab">
						<view class="nav nav-tabs">
							<view class="nav-item" v-for="(nav, index) in data.navs" :key="index">
								<view class="nav-item-btn" @tap="selectTab($event, index, data)">
									<image class="icon" :src="nav.id == data.isStandard ? nav.activeImg : nav.img"></image>
								</view>
							</view>
						</view>
						<view class="tab-content">
							<view class="tab-panel" v-show="data.isStandard == 1">
								<view class="form-item" >
									<view class="form-item-header">
										原因：
									</view>
									<view class="form-item-body">
										<textarea v-model="data.reason" class="form-control textarea" maxlength="250" ></textarea>
									</view>
								</view>
								<view class="form-item">
									<view class="form-item-header">
										拍照：
									</view>
									<view class="form-item-body">
										<view class="list list-p">
											<view class="list-group">
												
												<view class="list-item" v-for="(baseImage, index) in data.images" :key="index">
													<view class="card card-a" @tap="viewPic(item,index)">
														<view class="card-header">
														</view>
														<view class="delete" @tap.stop.prevent="delPic(data,index)">
															<image class="icon" mode="aspectFit" src="@/static/icon/delete-icon.png">
															</image>
														</view>
														<view class="card-body">
															<image class="icon" mode="aspectFit" :src="baseImage"></image>
														</view>
													</view>
												</view>
												
										
												<view class="list-item">
													<view class="card card-a upload" @tap="getPic(data)">
														<view class="card-body">
															<image class="icon" mode="aspectFit" src="@/static/icon/iv_pic_add.png"></image>
														</view>
													</view>
												</view>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="btns">
					<view class="btns-group" v-if="count == 1">
						<button class="btn btn-a" @tap="sendData">下一项（确定）</button>
					</view> 
					<view class="btns-group" v-else>
						<view class="btns-item">
							<button class="btn btn-a" @tap="redoPre">返回</button>
						</view>
						<view class="btns-item">
							<button class="btn btn-a" @tap="sendData">下一项（确定）</button>
						</view>
					</view>
					
				</view>
			</swiper-item>
		</swiper>
		
	</view>
</template>

<script>
	import {selectIsInspection, getDicList, getDicList1, insertDataToiletInspection, insertNoInspection, insertDataToiletInspectionLog} from '@/api/configure.js';
	import { getUserInfo, deepClone ,mergeUrls,getBaseImages, previewImage, chooseImage} from '@/util/util.js';
	import { pathToBase64, base64ToPath } from '@/util/mmmm-image-tools/index.js';
	import configUrl from '@/util/url.js';
	import FormGroup from '@/components/form-group/index.vue';
	export default {
		components: {
			FormGroup
		},
		data() {
			return {
				eventId: '',
				eventName: '',
				userId: '',
				userName: '',
				count: 0,
				curIndex: 0,
				inspectionid: '',
				reportData: [{
					type: 'addr',
					field: 'address',
					label: '我的位置',
					value: '',
					lnglats: '',
					gdx: '',
					gdy: ''
				}, {
					type: 'radioGroup',
					field: 'status',
					label: '状态',
					value: '0',
					options: [{
						label: '正常巡查',
						value: '0'
					}, {
						label: '无法巡检',
						value: '1'
					}]
				},{
					type: 'select',
					field: 'reason',
					label: '原因',
					options: [],
					index: null,
					value: '',
					isHide: true
				},{
					type: 'textarea',
					field: 'remark',
					label: '备注',
					value: '',
					isHide: true
				},{
					type: 'upload',
					field: 'images',
					label: '拍照',
					value: '',
					images: [],
					baseImages: [],
				}],
				answer_datas:[]
			}
		},
		methods: {
			selectTab(e, index, item) {
				item.isStandard = item.navs[index]['id'];
			},
			async getPic(obj) {
				let res = await chooseImage().catch((err) => {});;
				
				if (res) {
					let tempFilePaths = res.tempFilePaths.slice(0);
					
					obj.images = obj.images.concat(tempFilePaths);
					
					let baseImages = await getBaseImages(tempFilePaths);
					
					obj.baseImages = obj.baseImages.concat(baseImages);
				}
			},
			delPic(obj, index) {
				obj.images.splice(index, 1);
				obj.baseImages.splice(index, 1);
			},
			viewPic(obj, index) {
				previewImage({
					urls: obj.images,
					current: index
				})
			},
			async getDicList1() {
				let param = {
					type: 'toilet_no_inspection'
				}
				
				let {code, data} = await getDicList1(param);
				
				this.reportData.forEach( item => {
					if( item.field == 'reason' ) {
						item.options = data.slice(0)
					}
				});
			},
			async insertNoInspection() {
				let params = {
					toiletId: this.eventId,
					reason: '',
					remark: '',
					address: '',
					createUser: this.userId,
					createUserName: this.userName, //上报人姓名
					lng: '',
					lat: '',
					images: ''
				}
				
				let reason = this.reportData.find( item => item.field == 'reason');
				
				if(!reason.value){
					uni.showToast({
					    title: '原因不能为空',
					    duration: 2000,
						icon: 'none'
					});
					
					return ;
				}
				
				let remark = this.reportData.find( item => item.field == 'remark');
				
				if(!remark.value){
					uni.showToast({
					    title: '备注不能为空',
					    duration: 2000,
						icon: 'none'
					});
					
					return ;
				}
				
				let images = this.reportData.find( item => item.field == 'images');
				
				if(images.baseImages.length == 0){
					uni.showToast({
					    title: '请先拍照！',
					    duration: 2000,
						icon: 'none'
					});
					
					return ;
				}
				
				this.reportData.forEach( item => {
					if(item.field == 'address') {
						params.address = item.value;
						params.lng = item.lnglats && item.lnglats.split(' ')[0];
						params.lat = item.lnglats && item.lnglats.split(' ')[1];
					} else if(item.field == 'images') {
						let baseImages = item.baseImages.map(it => it.split(',')[1])
						params.images = baseImages.join(',')
					} else if(item.field == 'reason') {
						params.reason = item.value;
					} else if(item.field == 'remark') {
						params.remark = item.value;
					}else {
						
					}
				})
				
				let {data, code} = await insertNoInspection(params);
				
				if(code == 0) {
					uni.$emit('toilet.index.refresh');
					
					uni.showToast({
					    title: '提交成功',
					    duration: 2000,
						icon: 'none'
					});
					
					setTimeout(() => {
						this.back();
					}, 2000);
				}
			},
			async getDicList() {
				let {code, data} = await getDicList();
				
				if(code == 0) {
					data.forEach( item => {
						item.dicToiletsInspectLv2s.forEach( it => {
							let answer_data = {
								parent_name: item.name,
								parent_id:item.id,
								name: it.name,
								id:it.id,
								isStandard: 1,
								reason: '',
								images: [],
								baseImages: [],
								navs: [{
									id: 1,
									img: require('@/static/icon/iv_nohege_uncheck.png'),
									activeImg: require('@/static/icon/iv_nohege_checked.png'),
									name: '不合格'
								},{
									id: 0,
									img: require('@/static/icon/iv_hege_uncheck.png'),
									activeImg: require('@/static/icon/iv_hege_checked.png'),
									name: '合格'
								}]
							}
							
							
							this.answer_datas.push(answer_data);
						})
					})
				}
			},
			async selectIsInspection() {
				let param = {
					toiletId: this.eventId
				}
				
				let {data, code} = await selectIsInspection(param);
				
				if(code == 0) {
					if (data.status !== null) {
						this.count = data.count + 1;
						this.inspectionid = data.inspectionid;
					} else {
						
					}
				}
			},
			async insertDataToiletInspection(param){
				this.$refs.report.send();
				
				let images = this.reportData.find( item => item.field == 'images');
				
				if(images.baseImages.length == 0){
					uni.showToast({
					    title: '请先拍照！',
					    duration: 2000,
						icon: 'none'
					});
					
					return ;
				}
				
				let address = this.reportData.find( item => item.field == 'address');
				
				if(!address.value || !address.lnglats){
					uni.showToast({
					    title: '其选择或输入地址',
					    duration: 2000,
						icon: 'none'
					});
					return ;
				}
				
				this.reportData.forEach( item => {
					if(item.field == 'address') {
						param.address = item.value;
						param.lng = item.lnglats && item.lnglats.split(' ')[0];
						param.lat = item.lnglats && item.lnglats.split(' ')[1];
					} else if(item.field == 'images') {
						let baseImages = item.baseImages.map(it => ({image: it.split(',')[1]}))
						param.images = JSON.stringify(baseImages);
					} else {
						
					}
				})
				
				let {code, data} = await insertDataToiletInspection(param);
				 
				if(code == 0) {
					this.inspectionid = data;
					
					uni.showToast({
					    title: '提交成功',
					    duration: 2000,
						icon: 'none'
					});
					
					this.count = this.count + 1;
				}
			},
			async insertDataToiletInspectionLog(param) {
				let index = this.count - 1;
				
				
				let targetData = this.answer_datas[index];
				
				if(targetData.isStandard == 1){
					if(targetData.baseImages.length == 0) {
						uni.showToast({
						    title: '请先拍照',
						    duration: 2000,
							icon: 'none'
						});
						
						return ;
					}
				}
				
				
				param.inspectionlv1 = targetData.parent_id;
				param.inspectionlv2 = targetData.id;
				param.isStandard = targetData.isStandard;
				
				if(param.isStandard == 1){
					param.remark = targetData.reason;
					
					let baseImages = targetData.baseImages.map(it => ({image: it.split(',')[1]}))
					param.images = JSON.stringify(baseImages);
				}
				
				param.flag = (index == this.answer_datas.length -1);
				
				let {code, data} = await insertDataToiletInspectionLog(param);
				
				if(code == 0){
					uni.$emit('toilet.index.refresh');
					
					uni.showToast({
					    title: '提交成功',
					    duration: 2000,
						icon: 'none'
					});
					
					if(param.flag) {
						setTimeout(() => {
							this.back();
						}, 2000)
					} else {
						this.count = this.count + 1;
					}
				}
			},
			redoPre() {
				this.count = this.count - 1;
			},
			async sendData() {
				this.$refs.report.send();
				
				let status = this.reportData.find( item => item.field == 'status');
				
				if(status.value == '1'){
					this.insertNoInspection();
					
					return;
				}
				
				let param={
					inspectionId: this.inspectionid || '',
					inspectionlv1: '',
					inspectionlv2: '',
					isStandard: '',
					remark: '',
				    images: '',//照片
				    flag: false,
				    toiletId: this.eventId,
				    nfcCode: '',
				    address: '',//详细地址
				    lng: '',
				    lat: '',
					createUser: this.userId,
					userName: this.userName, //上报人姓名
				};
				
				if(this.inspectionid){
					await this.insertDataToiletInspectionLog(param);
				} else {
					await this.insertDataToiletInspection(param);
				}
			},
			refresh() {
				this.setMapPos();
			},
			back() {
			    uni.navigateBack({  
			        delta: 1
			    });  
			},
			
			async init() {
				await this.selectIsInspection();
				await this.getDicList();
				await this.getDicList1();
			}
		},
		onLoad(option) {
			this.eventId = option.id;
			this.eventName = option.name;
			
			let coordinates = JSON.parse(option.st_asgeojson)['coordinates'];
			
			this.reportData.forEach( item => {
				if(item.field == 'address'){
					item.gdx = coordinates[0]; //lo
					item.gdy = coordinates[1]; //la
				}
			})
			
			
			let userInfo = getUserInfo();
						
			if (userInfo) {
				this.userId = userInfo['userId'];
				this.userName = userInfo['userName'];
			}
			
			this.init();
			
		},
		onReady() {},
		onUnload() {
		},
		onBackPress(options) {
			let _this = this;
			
			if (options.from === 'navigateBack') {  
				return false;  
			}  
			
			uni.showModal({
			    content: '确定退出当前页面吗？',
			    success(res) {
			        if (res.confirm) {
			           _this.back();  
			        } else if (res.cancel) {
			          
			        }
			    }
			});
					   
			return true;  
		}
	}
</script>

<style lang="scss">
	.form{
		padding: 40rpx 0rpx 0rpx;
		.form-header{
			margin-bottom: 20rpx;
			padding: 0rpx 30rpx 0rpx;
			font-size: 40rpx;
			color: #f29004;
			line-height: 120%;
			font-weight: bold;
		}
	}
	
	.title{
		margin-bottom: 20rpx;
		font-size: 28rpx;
		line-height: 120%;
		color: #5d5d5d;
	}
	
	.sub-title{
		margin-bottom: 20rpx;
		font-size: 28rpx;
		line-height: 120%;
		color: #5d5d5d;
	}
	
	.btns {
		background-color: #ffffff;
	
		.btns-group {
			padding: 17rpx 30rpx;
			display: flex;
	
			.btns-item {
				width: 50%;
				padding: 0rpx 10rpx;
			}
		}
	
	}
	
	.btn {
		width: 100%;
		padding: 20rpx 0px;
		font-size: 24rpx;
		line-height: 120%;
		color: #fff;
		text-align: center;
		border: none;
		border-radius: 6rpx;
		background: none;
	
		&:after {
			display: none;
		}
	
		&.btn-a {
			background-color: #f29004;
		}
	}
	
	.form-group {
		padding: 0rpx 30rpx;
	
		.form-item {
			margin-bottom: 40rpx;
	
			.form-item-header {
				margin-bottom: 20rpx;
				padding: 13rpx 0rpx 13rpx 0rpx;
				font-size: 28rpx;
				line-height: 120%;
				color: #5d5d5d;
			}
	
			.form-item-body {
				padding: 0rpx 0rpx 0rpx 0rpx;
	
				.form-control-static {
					padding: 20rpx;
					font-size: 24rpx;
					border-radius: 10rpx;
					line-height: 120%;
					box-sizing: border-box;
				}
	
				.form-control {
					width: 100%;
					font-size: 24rpx;
					border-radius: 10rpx;
					line-height: 120%;
					box-sizing: border-box;
					border: 1px solid #c4c4c4;
					height: 56rpx;
					padding: 6rpx 16rpx;
	
					&.textarea{
						min-height: 200rpx;
					}
				}
			}
	
			&.form-item-hor {
				display: flex;
	
				.form-item-header {
					width: 140rpx;
					box-sizing: border-box;
					margin-bottom: 0rpx;
				}
	
				.form-item-body {
					padding: 0rpx 0rpx 0rpx 0rpx;
					width: calc(100% - 140rpx);
					box-sizing: border-box;
				}
			}
	
			.form-item-tip {
				padding: 8rpx 0rpx;
				font-size: 28rpx;
				line-height: 120%;
				color: #d81e06;
			}
		}
	}
	
	
	
	.select {
		border: 1rpx solid #c4c4c4;
		border-radius: 10rpx;
		position: relative;
		top: 0rpx;
		left: 0rpx;
	
		.selected {
			padding: 10rpx 52rpx 10rpx 16rpx;
			font-size: 24rpx;
			line-height: 32rpx;
			color: #5d5d5d;
		}
	
		.select-icon {
			width: 52rpx;
			height: 52rpx;
			position: absolute;
			top: 0rpx;
			right: 0rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
	
	.search-wrap {
		padding: 10rpx 0rpx;
	}
	
	.search {
		display: flex;
		justify-content: space-between;
	
		.search-control {
			width: calc(100% - 160rpx);
			padding: 18rpx;
			font-size: 24rpx;
			line-height: 32rpx;
			border: 1rpx solid #f29004;
			border-radius: 10rpx;
		}
	
		.search-btn {
			width: 100rpx;
			padding: 20rpx 0rpx;
			margin: 0rpx;
			font-size: 24rpx;
			line-height: 32rpx;
			background-color: #f29004;
			color: #ffffff;
		}
	}
	
	.card {}
	
	.card-address {
		position: relative;
		top: 0rpx;
		left: 0rpx;
	
		.card-content {
			height: 120rpx;
			margin: 0rpx 100rpx 0rpx 0rpx;
			padding: 20rpx;
			font-size: 24rpx;
			border-radius: 10rpx;
			line-height: 120%;
			box-sizing: border-box;
			border: 1px solid #c4c4c4;
		}
	
		.card-icon {
			width: 80rpx;
			height: 80rpx;
			position: absolute;
			top: 0rpx;
			right: 0rpx;
			margin: 20rpx 0rpx 20rpx 10rpx;
	
			.icon {
				width: 100%;
				height: 100%;
			}
		}
	}
	
	.card-a {
		width: 223rpx;
		margin: 0rpx auto;
		border-radius: 5rpx;
		border: 1rpx solid #a2a2a2;
		position: relative;
		top: 0rpx;
		left: 0rpx;
	
		.card-body {
			height: 143rpx;
	
			.icon {
				width: 100%;
				height: 100%;
			}
		}
	
		&.upload {
			border: none;
		}
	
		.card-header {
			width: 100%;
			height: 31rpx;
			position: absolute;
			top: 0rpx;
			left: 0rpx;
			background-color: #000000;
			opacity: 0.3;
			z-index: 2;
		}
	
		.delete {
			width: 31rpx;
			height: 31rpx;
			position: absolute;
			top: 0rpx;
			right: 0rpx;
			z-index: 3;
			display: flex;
			justify-content: center;
			align-items: center;
	
			.icon {
				width: 20rpx;
				height: 20rpx;
			}
		}
	
	}
	
	.list {
		&.list-p {
			.list-group {
				display: flex;
				flex-wrap: wrap;
	
				.list-item {
					margin-bottom: 20rpx;
					width: 33.33%;
				}
			}
		}
	
		&.list-types {
			width: 600rpx;
			background-color: #ffffff;
	
			.list-group {
				padding: 20rpx 0rpx 0rpx;
	
				.list-item {
					margin-bottom: 10rpx;
					position: relative;
					top: 0rpx;
					left: 0rpx;
	
					&:after {
						content: '';
						background-color: #999;
						opacity: 0.5;
						height: 1rpx;
						position: absolute;
						right: 20rpx;
						bottom: 0rpx;
						left: 20rpx;
					}
	
					.list-item-btn {
						padding: 13rpx 20rpx;
						font-size: 28rpx;
						line-height: 120%;
						color: #5d5d5d;
					}
				}
			}
		}
	}
	
	.swiper-item {
		.image {
			width: 100%;
			height: 300rpx;
		}
	}
	
	.tab{
		.nav-tabs{
			display: flex;
			justify-content: center;
			.nav-item{
				padding:0rpx 20rpx;
				.nav-item-btn{
					.icon{
						width: 160rpx;
						height: 120rpx;
					}
					
				}
			}
		}
	}
	
	.carousel{
		height: 1100rpx;
	}
	
	
</style>
